package goperf

import (
	"fmt"
	"gitee.com/ha666/logs"
	"golang.org/x/net/proxy"
	"net"
	"strconv"
	"strings"
)

//获取随机server连接
func getRandomConn() (net.Conn, error) {
	destIps := strings.Split(*fDestIps, ",")
	var err error
	proxyPort := 10000
	proxyPorts := strings.Split(*fProxyPorts, ",")
	if *proxyPortType {
		proxyPort, err = strconv.Atoi(proxyPorts[0])
		if err != nil {
			logs.Error(err)
			panic(err)
		}
	} else {
		min, err := strconv.Atoi(proxyPorts[0])
		if err != nil {
			logs.Error(err)
			panic(err)
		}
		max, err := strconv.Atoi(proxyPorts[len(proxyPorts)-1])
		if err != nil {
			logs.Error(err)
			panic(err)
		}
		proxyPort = int(RangeRand(int64(min), int64(max)))
	}
	dialer, err := proxy.SOCKS5("tcp4", fmt.Sprintf("%s:%d", *fProxyIp, proxyPort), &proxy.Auth{User: *user, Password: *pwd}, proxy.Direct)
	if err != nil {
		return nil, err
	}

	randomIpIndex := int(RangeRand(0, int64(len(destIps)-1)))
	destIp := destIps[randomIpIndex]

	conn, err := dialer.Dial("tcp4", fmt.Sprintf("%s:%d", destIp, *fDestPort))
	if err != nil {
		dialer = nil
		logs.Error(err)
		return nil, err
	}
	return conn, nil
}
